﻿/**
 * Copyright(c) Live2D Inc. All rights reserved.
 *
 * Use of this source code is governed by the Live2D Open Software license
 * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
 */

#include "../include/Live2dPal.hpp"
#include <cstdio>
#include <stdarg.h>
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <Model/CubismMoc.hpp>
#include "../include/Live2dDefine.hpp"
#include "../../libcat/include/util/base.hpp"
#include "../../libcat/include/util/utf8.h"
#include "../../libcat/include/util/cmem.hpp"

using std::endl;
using namespace Csm;
using namespace std;
using namespace Live2dDefine;

double Live2dPal::s_currentFrame = 0.0;
double Live2dPal::s_lastFrame = 0.0;
double Live2dPal::s_deltaTime = 0.0;
wchar_t wfilename[255];

csmByte* Live2dPal::LoadFileAsBytes(const string filePath, csmSizeInt* outSize)
{ 
    //filePath;//    
    size_t wfilenameSize = utf8_to_wchar(filePath.c_str(), 0, wfilename, 255);
    wfilename[wfilenameSize] = '\0';    

    int size = 0;
    struct _stat64 statBuf;
    if (_wstati64(wfilename, &statBuf) == 0)
    {
        size = statBuf.st_size;
    }

    std::fstream file;
    char* buf = (char *)bmalloc(size);

    file.open(wfilename, std::ios::in | std::ios::binary);
    if (!file.is_open())
    {
        if (DebugLogEnable)
        {
            PrintLog("file open error");
        }
        return NULL;
    }
    file.read(buf, size);
    file.close();

    *outSize = size;
    return reinterpret_cast<csmByte*>(buf);
}

void Live2dPal::ReleaseBytes(csmByte* byteData)
{
    bfree(byteData);
}

csmFloat32  Live2dPal::GetDeltaTime()
{
    return static_cast<csmFloat32>(s_deltaTime);
}

void Live2dPal::UpdateTime()
{
    s_currentFrame = glfwGetTime();
    s_deltaTime = s_currentFrame - s_lastFrame;
    s_lastFrame = s_currentFrame;
}

void Live2dPal::PrintLog(const csmChar* format, ...)
{
    va_list args;
    csmChar buf[256];
    va_start(args, format);
    vsnprintf_s(buf, sizeof(buf), format, args); // 標準出力でレンダリング
#ifdef CSM_DEBUG_MEMORY_LEAKING
// メモリリークチェック時は大量の標準出力がはしり重いのでprintfを利用する
    blog(LOG_DEBUG, "[live2d]%s", buf);
#else
    blog(LOG_DEBUG, "[live2d]%s",buf);
#endif
    va_end(args);
}

void Live2dPal::PrintMessage(const csmChar* message)
{
    PrintLog("%s", message);
}
